package com.example.mcp.controller;

import com.example.mcp.service.McpClientService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * MCP服务器状态检查控制器
 */
@RestController
@RequestMapping("/api/mcp-status")
@CrossOrigin(origins = "*")
public class McpServerStatusController {

    private static final Logger logger = LoggerFactory.getLogger(McpServerStatusController.class);

    @Autowired
    private McpClientService mcpClientService;

    @Value("${mcp.client.server-url:http://localhost:8081}")
    private String serverUrl;

    private final RestTemplate restTemplate = new RestTemplate();

    /**
     * 检查MCP服务器连接状态
     */
    @GetMapping("/check")
    public ResponseEntity<Map<String, Object>> checkServerStatus() {
        logger.info("🔍 检查MCP服务器状态: {}", serverUrl);
        
        Map<String, Object> result = Map.of(
            "serverUrl", serverUrl,
            "clientInitialized", mcpClientService.isInitialized(),
            "timestamp", System.currentTimeMillis()
        );
        
        return ResponseEntity.ok(result);
    }

    /**
     * 测试MCP服务器连接
     */
    @GetMapping("/test-connection")
    public ResponseEntity<Map<String, Object>> testConnection() {
        logger.info("🧪 测试MCP服务器连接: {}", serverUrl);
        
        try {
            // 检查MCP客户端是否已初始化
            if (!mcpClientService.isInitialized()) {
                Map<String, Object> result = Map.of(
                    "success", false,
                    "serverUrl", serverUrl,
                    "message", "MCP客户端未初始化",
                    "timestamp", System.currentTimeMillis()
                );
                return ResponseEntity.ok(result);
            }
            
            // 尝试ping服务器来验证连接
            try {
                String pingResult = mcpClientService.ping().get(5, TimeUnit.SECONDS);
                logger.info("✅ MCP服务器ping成功: {}", pingResult);
                
                Map<String, Object> result = Map.of(
                    "success", true,
                    "serverUrl", serverUrl,
                    "clientStatus", "已初始化",
                    "pingResult", pingResult,
                    "message", "MCP服务器连接正常",
                    "timestamp", System.currentTimeMillis()
                );
                
                return ResponseEntity.ok(result);
                
            } catch (Exception pingException) {
                logger.error("❌ MCP服务器ping失败", pingException);
                
                Map<String, Object> result = Map.of(
                    "success", false,
                    "serverUrl", serverUrl,
                    "clientStatus", "已初始化但连接失败",
                    "error", pingException.getMessage(),
                    "message", "MCP客户端已初始化但无法与服务器通信",
                    "timestamp", System.currentTimeMillis()
                );
                
                return ResponseEntity.ok(result);
            }
            
        } catch (Exception e) {
            logger.error("❌ MCP服务器连接失败", e);
            
            Map<String, Object> result = Map.of(
                "success", false,
                "serverUrl", serverUrl,
                "error", e.getMessage(),
                "message", "MCP服务器连接失败，请检查服务器是否运行",
                "timestamp", System.currentTimeMillis()
            );
            
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 测试MCP客户端服务
     */
    @GetMapping("/test-client")
    public ResponseEntity<Map<String, Object>> testClient() {
        logger.info("🧪 测试MCP客户端服务");
        
        try {
            // 检查MCP客户端是否已初始化
            if (!mcpClientService.isInitialized()) {
                Map<String, Object> response = Map.of(
                    "success", false,
                    "message", "MCP客户端未初始化",
                    "timestamp", System.currentTimeMillis()
                );
                return ResponseEntity.ok(response);
            }
            
            // 由于MCP客户端已初始化，说明服务正常
            Map<String, Object> response = Map.of(
                "success", true,
                "clientStatus", "已初始化",
                "message", "MCP客户端服务正常",
                "timestamp", System.currentTimeMillis()
            );
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("❌ MCP客户端测试失败", e);
            
            Map<String, Object> response = Map.of(
                "success", false,
                "error", e.getMessage(),
                "message", "MCP客户端服务异常",
                "timestamp", System.currentTimeMillis()
            );
            
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 获取MCP服务器信息
     */
    @GetMapping("/info")
    public ResponseEntity<Map<String, Object>> getServerInfo() {
        Map<String, Object> info = Map.of(
            "serverUrl", serverUrl,
            "sseEndpoint", "/sse",
            "clientInitialized", mcpClientService.isInitialized(),
            "suggestions", Map.of(
                "checkServer", "确保MCP服务器运行在 " + serverUrl,
                "checkNetwork", "检查网络连接和防火墙设置",
                "checkLogs", "查看MCP服务器日志",
                "restartServer", "尝试重启MCP服务器"
            ),
            "timestamp", System.currentTimeMillis()
        );
        
        return ResponseEntity.ok(info);
    }
    
    /**
     * 手动重新初始化MCP客户端
     */
    @PostMapping("/reinitialize")
    public ResponseEntity<Map<String, Object>> reinitializeClient() {
        logger.info("🔄 手动重新初始化MCP客户端");
        
        try {
            // 强制重新初始化MCP客户端
            mcpClientService.forceReinitialize();
            
            // 检查重新初始化后的状态
            boolean isHealthy = mcpClientService.isConnectionHealthy();
            
            Map<String, Object> result = Map.of(
                "success", true,
                "message", "MCP客户端重新初始化完成",
                "connectionHealthy", isHealthy,
                "timestamp", System.currentTimeMillis()
            );
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            logger.error("❌ MCP客户端重新初始化失败", e);
            
            Map<String, Object> result = Map.of(
                "success", false,
                "error", e.getMessage(),
                "message", "MCP客户端重新初始化失败",
                "timestamp", System.currentTimeMillis()
            );
            
            return ResponseEntity.ok(result);
        }
    }
    
    /**
     * 检查连接健康状态
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> checkHealth() {
        logger.info("🏥 检查MCP连接健康状态");
        
        try {
            boolean isHealthy = mcpClientService.isConnectionHealthy();
            boolean isInitialized = mcpClientService.isInitialized();
            
            Map<String, Object> result = Map.of(
                "success", true,
                "connectionHealthy", isHealthy,
                "clientInitialized", isInitialized,
                "message", isHealthy ? "连接健康" : "连接不健康",
                "timestamp", System.currentTimeMillis()
            );
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            logger.error("❌ 健康检查失败", e);
            
            Map<String, Object> result = Map.of(
                "success", false,
                "error", e.getMessage(),
                "message", "健康检查失败",
                "timestamp", System.currentTimeMillis()
            );
            
            return ResponseEntity.ok(result);
        }
    }
}
